package com.until;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Testcyclicbarrier {
    public static void main(String[] args) {

        final CyclicBarrier barrier1 = new CyclicBarrier(2, new Runnable() {
            public void run() {
                System.out.println("BarrierAction 1 executed ");
            }
        });
        final CyclicBarrier barrier2 = new CyclicBarrier(2, new Runnable() {
            public void run() {
                System.out.println("BarrierAction 2 executed ");

            }
        });
        for (int i=0;i<3;i++)
        {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName()+"waited barrier1");
                        barrier1.await();
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName()+"waited barrier2");
                        barrier2.await();

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }


    }

}
class CyclicBarrierRunnable implements Runnable {

    CyclicBarrier barrier1 = null;
    CyclicBarrier barrier2 = null;

    CyclicBarrierRunnable(
            CyclicBarrier barrier1,
            CyclicBarrier barrier2) {

        this.barrier1 = barrier1;
        this.barrier2 = barrier2;
    }

    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +
                    " waiting at barrier 1");
            this.barrier1.await();

            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +
                    " waiting at barrier 2");
            this.barrier2.await();

            System.out.println(Thread.currentThread().getName() +
                    " done!");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
